<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    // 注册用户
    public function register(Request $request){

        $data = $request->all();
        $token = md5(uniqid(md5(microtime(true)),true));

        if($this->check_name($data['name'])){
            return response()->json(['meta'=>['status'=>3000,'msg'=>'该用户名已经存在!']]);
        }

        $user = User::create([
            'name' => $data['name'],
            'email'=>$data['email'],
            'password' => bcrypt($data['password']),
            'api_token' =>$token
        ]);
        return response()->json(['meta'=>['status'=>201,'msg'=>'用户添加成功'],'data'=>$user]);

    }

    // 用户唯一性验证
    private function check_name($name){
        return (bool) User::where('name',$name)->first();
    }

    // 头像上传

    public function upload(Request $request){

      // 1 获取上传图片
      $file = $request->file("pic");
      $path = \base_path("/public/upload/");
        
      // 2 上传头像 
      $ext = $file->getClientOriginalExtension();
      $picName = time().rand(0,999).".".$ext;
      $file->move($path,$picName);

     
      // 3 保存到数据库表 
      $user = \Auth::guard('api')->user();

      $user->avatar = $picName;
      $bool = $user->save();
      $user->avatar = config('app.upload').$picName;
      
      // 用户反馈
      if($bool){
          return response()->json(['meta'=>['msg'=>'头像上传成功!','status'=>200],'user'=>$user]);
      }else{
          return response()->json(['meta'=>['msg'=>'头像上传失败!','status'=>3000],'user'=>$user]);
      } 
      
    }
     
     //用户登录
     public function login(Request $request){

        $params = \request(["name","password"]);

        $data = User::where("name",$request->name)->first();

        $data->avatar =  $data->avatar ? config('app.upload').$data->avatar :false;

        if(\Auth::guard("web")->attempt($params)){
            return response()->json(['meta'=>['status'=>200,'msg'=>'登录成功!'],'data'=>$data]);
        }else{
           return response()->json(['meta'=>['status'=>3000,'msg'=>'账号或密码错误!']]);
        }

    }

    // 地址列表
    public function addresses(Request $request){

        $user = Auth::guard('api')->user();
        return response()->json(['meta'=>['status'=>200,'msg'=>'请求成功!'],'data'=>$user->addresses]);

    }

}
